import { Toast, Dialog } from 'vant';
import Service from './service';
import { common } from '@/utils';

export default class Http extends Service {
  constructor() {
    super();
    this.config = {
      action: this.$t('operation'),
      isCheckToken: true,
      isAvoidShowError: true,
      isAvoidShowSuccess: false,
      isAvoidSuccessFn: null,
      scm: 'TMS',
      formData: false,
    };
  }

  fetch(type, url, params = {}, config = {}, loading) {
    Toast.clear();
    this.showLoading(loading);

    const fetchData = new Promise((resolve, reject) => {
      this.instance[type](
        url,
        type === 'get' ? { params, ...config } : params,
        type === 'get' ? null : config,
      )
        .then(res => {
          if (config.isAvoidShowError && !res.flag) {
            Toast({
              message: res.msg,
              position: 'bottom',
            });
          }
          if (config.isAvoidShowSuccess && res.flag) {
            Dialog.alert({
              title: this.$t('hint'),
              message: `${config.action}${this.vm.$t('success')}`,
            }).then(() => {
              if (Object.prototype.toString.call(config.isAvoidSuccessFn) === '[object Function]') {
                config.isAvoidSuccessFn();
              }
            });
          }
          return resolve(res);
        })
        .catch(error => reject(error))
        .finally(() => {
          if (loading) {
            this.closeLoading();
          }
        });
    });

    return fetchData;
  }

  get({ url, params = {}, config = {} }, loading) {
    return this.fetch('get', url, params, { ...this.config, ...config }, loading);
  }

  post({ url, params = {}, config = {} }, loading) {
    return this.fetch('post', url, params, { ...this.config, ...config }, loading);
  }

  uploadFile({ url, filePath, fileType = 'image', formData, completed, scm = 'TMS' }) {
    if (!this.token) {
      return common.noToken();
    }

    const task = window.plus.uploader.createUpload(
      `${this.baseUrl + this.scmDomain[scm] + url}?token=${this.token}`,
      { method: 'POST', priority: 100, timeout: 0 },
      completed,
    );
    task.addFile(filePath, { key: fileType });

    for (const key in formData) {
      if (Object.prototype.hasOwnProperty.call(formData, key)) {
        task.addData(key, formData[key]);
      }
    }

    task.start();
  }

  closeLoading() {
    setTimeout(() => {
      Toast.clear();
    }, 500);
  }

  showLoading({ message = this.$t('loading'), show = false } = {}) {
    if (show) {
      Toast.loading({
        forbidClick: true,
        message,
        duration: 0,
        overlay: true,
      });
    }
  }
}
